package cs6238.server;

import java.io.File;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;

import cs6238.common.CertificateHelper;
import cs6238.common.Configuration;

/**
 * A class for managing a library of certificates
 * @author robertmparker
 *
 */
public class ClientCertManager {
	
	/**
	 * Get the folder that stores the client certs, create if doesn't exist
	 * @return
	 */
	private static File getClientCertFolder(){
		Configuration serverConfig = Configuration.loadServerSettings();
		String folderPath = serverConfig.getSetting(Configuration.CLIENT_CERT_FOLDER_PATH);
		
		File folder = new File(folderPath);
		if(!folder.exists()){
			folder.mkdirs();
		}
		
		return folder;
	}
	
	/**
	 * Store the certificate
	 * @param cert
	 */
	public static void storeCertificate(X509Certificate cert){
		String hostname = CertificateHelper.getHostname(cert);
		String filepath = createPath(hostname);
		try {
			CertificateHelper.writeCertificate(cert, filepath);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Get all the filenames, except any that start with a period
	 * @return
	 */
	public static List<String> getHostnames(){
		String[] fileList = getClientCertFolder().list();
		
		ArrayList<String> result = new ArrayList<String>();
		
		for(String filename : fileList){
			if(!filename.startsWith(".")){
				result.add(filename);
			}
		}
		
		return result;
	}
	
	/**
	 * Get the certificate
	 * @param hostname
	 * @return
	 */
	public static X509Certificate getCertificate(String hostname){
		String certPath = createPath(hostname);
		try {
			return CertificateHelper.readCertificate(certPath);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	
	
	/**
	 * Helper function
	 * @param filename
	 * @return
	 */
	private static String createPath(String filename){
		return getClientCertFolder().getPath() + File.separator + filename;
	}

	public static void deleteAllCertificates() {
		String[] files = getClientCertFolder().list();
		
		for(String filename : files){
			if(!filename.startsWith(".")){
				new File(filename).delete();
			}
		}
	}

}
